<script setup lang="ts">
import type {
  AllTradeMark,HasSaleAttr,HasSaleAttrResponseData,SaleAttrResponseData,
  SaleAttrValue,SpuData,SpuHasImg,SpuImg,Trademark,SaleAttr
} from "@/api/product/spu/type.ts";
import {reqAllSaleAttr, reqAllTradeMark, reqSpuHasSaleAttr, reqSpuImageList,reqAddOrUpdateSpu} from '@/api/product/spu/index.ts'
import {computed, nextTick, ref} from "vue";
import {ElMessage, UploadProps} from "element-plus";

const $emit = defineEmits(['changeScene'])
/**
 * 取消或修改则改变场景
 */
const cancel = () => {
  $emit('changeScene',{flag:0,params:SpuParams.value.id?'update':''})
}
const allTradeMark = ref<Trademark[]>([])
const imageList =ref<SpuImg[]>([])
const saleAttr = ref<SaleAttr[]>([])
const allSaleAttr = ref<HasSaleAttr[]>([])
// 存储已有的spu对象
const SpuParams = ref<SpuData>({
  spuName:'',
  description:'',
  tmId:'',
  spuImageList:[],
  spuSaleAttrList:[],
  category3Id:'',
})
//子组件书写一个方法
const initHasSpuData = async (spu:SpuData) => {
  SpuParams.value=spu
  //获取全部品牌的数据
  const res1:AllTradeMark= await reqAllTradeMark()
  allTradeMark.value=res1.data
  //获取某一个品牌旗下全部售卖商品的图片
  const res2:SpuHasImg = await reqSpuImageList(spu.id as number)
  imageList.value=res2.data.map(item=>{
    return {
      name:item.imgName,
      url:item.imgUrl
    }
  })
  //获取已有的SPU销售属性的数据
  const res3:SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  saleAttr.value=res3.data
  //获取整个项目全部SPU的销售属性
  const res4:HasSaleAttrResponseData = await reqAllSaleAttr()
  allSaleAttr.value=res4.data
}
/**
 * 上传成功
 */
const handleSuccess = () => {
  ElMessage({
    type:'success',
    message:'上传成功'
  })
}
/**
 * 上传文件之前的钩子
 * @param rawFile
 */
const beforeUpload:UploadProps['beforeUpload'] = (rawFile) => {
  if(rawFile.type=='image/png'||rawFile.type=='image/jpeg'||rawFile.type=='image/gif'){
    if(rawFile.size/1024/1024<3){
      return  true
    }else{
      ElMessage({
        type:'error',
        message:'上传文件大小小于4M'
      })
      return  false
    }
  }else{
    ElMessage({
      type:'error',
      message:'上传文件格式必须是PNG|JPG|GIF'
    })
    return false;
  }
}
//图片预览的显示控制
const dialogVisible=ref<boolean>(false)
//图片预览的图片链接
const dialogImageUrl =ref<string>()
/**
 * 照片墙点击预览按钮的时候触发的钩子
 * @param uploadFile
 */
const handlePictureCardPreview:UploadProps['onPreview'] = (uploadFile) => {
  dialogVisible.value=true
  dialogImageUrl.value=uploadFile.url
}
/**
 * 移除图片
 */
const handleRemove:UploadProps['onRemove'] = () => {
  ElMessage({
    type:'success',
    message:'移除成功'
  })
}
//计算SPU还未拥有的销售属性
const unSelectSaleAttr = computed(()=>{
  return allSaleAttr.value.filter(item => {
    return saleAttr.value.every(item1 => {
      return item.name != item1.saleAttrName
    })
  })
})
//将来收集还未选择的销售属性的ID与属性值的名字
const saleAttrIdAndValueName =ref<string>('')
/**
 * 添加销售属性
 */
const addSaleAttr = () => {
  const [baseSaleAttrId,saleAttrName] = saleAttrIdAndValueName.value.split(':')
  const newSaleAttr:SaleAttr={
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList:[]
  }
  saleAttr.value.push(newSaleAttr)//追加到数组当中
  saleAttrIdAndValueName.value=''//清空收集的数据
}
//存储销售属性值
const saleAttrValueInput = ref<any>([])
/**
 * 添加属性的编辑模式
 * @param row
 */
const toEdit = (row:SaleAttr,index:number) => {
  row.flag=true
  row.saleAttrValue=''
  nextTick(()=>{
    saleAttrValueInput.value[index]?.focus()
  })
}
/**
 * 添加属性完成
 * @param row
 */
const toLook = (row:SaleAttr) => {
  const {baseSaleAttrId,saleAttrValue} = row
  const newSaleAttrValue:SaleAttrValue={
    saleAttrName: "",
    baseSaleAttrId,
    saleAttrValueName:(saleAttrValue as string)
  }
  // 非空的判断
  if(!saleAttrValue?.toString().trim()){
    return ElMessage({
      type:'warning',
      message:'内容不能为空'
    })
  }
  //判断属性值的数组
  const repeat = row.spuSaleAttrValueList.find(item=>{
    return item.saleAttrValueName === saleAttrValue
  })
  if(repeat) {
    return ElMessage({
      type:'error',
      message:'属性值重复'
    })
  }
  //追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag=false
}
/**
 * 保存数据
 */
const save = async () => {
  //整理照片属性的数据
  SpuParams.value.spuImageList = imageList.value.map((item:any)=>{
    return {
      imgName:item.name,
      imgUrl:(item.response&&item.response.data)||item.url
    }
  })
  //整理销售属性的数据
  SpuParams.value.spuSaleAttrList=saleAttr.value
  const res:any = await reqAddOrUpdateSpu(SpuParams.value)
  // console.log(res)
  if(res.code==200){
    ElMessage({
      type:'success',
      message:SpuParams.value.id?'更新成功':'添加成功'
    })
    $emit('changeScene',{flag:0,params:SpuParams.value.id?'update':'add'})
  }else {
    ElMessage({
      type:'error',
      message:SpuParams.value.id?'更新失败':'添加失败'
    })
  }
}
/**
 * 添加一个新的SPU初始化请求方法
 */
const initAddSpu = async (c3Id:number|string) => {
  //添加前情况数据
  Object.assign(SpuParams.value,{
    id:'',
    spuName:'',
    description:'',
    tmId:'',
    spuImageList:[],
    spuSaleAttrList:[],
    category3Id:'',
  })
  imageList.value=[]
  saleAttr.value=[]
  saleAttrIdAndValueName.value=''
  // 存储三级分类ID
  SpuParams.value.category3Id=c3Id
  //获取全部品牌的数据
  const res1:AllTradeMark= await reqAllTradeMark()
  allTradeMark.value=res1.data
  //获取整个项目全部SPU的销售属性
  const res4:HasSaleAttrResponseData = await reqAllSaleAttr()
  allSaleAttr.value=res4.data
}
defineExpose({initHasSpuData,initAddSpu})
</script>

<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请你输入SPU名称" v-model="SpuParams.spuName"></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择品牌" v-model="SpuParams.tmId">
          <el-option :label="item.tmName" v-for="item in allTradeMark" :key="item.id" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input placeholder="请你输入SPU描述" type="textarea" v-model="SpuParams.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
            action="/api/admin/product/fileUpload"
            list-type="picture-card"
            v-model:file-list="imageList"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%"/>
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select :placeholder="unSelectSaleAttr.length?`还未选择${unSelectSaleAttr.length}个`:'无数据'" v-model="saleAttrIdAndValueName">
          <el-option :value="`${item.id}:${item.name}`" :label="item.name" v-for="item in unSelectSaleAttr" :key="item.id"></el-option>
        </el-select>
        <el-button style="margin-left: 10px;" type="primary" icon="Plus" :disabled="!saleAttrIdAndValueName" @click="addSaleAttr">添加属性值</el-button>
        <el-table border style="margin: 10px 0;" :fit="true" :data="saleAttr">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="销售属性名字" prop="saleAttrName"></el-table-column>
          <el-table-column label="销售属性值">
            <template #default="{row,$index}">
              <el-tag v-for="(item,index) in row.spuSaleAttrValueList"
                      closable :key="item.name"
                      style="margin: 0 8px;"
                      @close="row.spuSaleAttrValueList.splice(index,1)"
              >{{item.saleAttrValueName}}</el-tag>
              <el-input
                  placeholder="请输入属性值"
                  size="small"
                  style="width: 120px;"
                  v-if="row.flag==true"
                  v-model="row.saleAttrValue"
                  :ref="(vc:any)=>saleAttrValueInput[$index]=vc"
                  @blur="toLook(row)"
              ></el-input>
              <el-button type="success" size="small" icon="Plus" @click="toEdit(row,$index)" v-else></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #default="{index}">
              <el-button type="danger" size="small" icon="Delete" @click="saleAttr.splice(index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left: 10px;" type="primary" @click="save" :disabled="!(saleAttr.length>0)">保存</el-button>
        <el-button style="margin-left: 10px;" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
 .avatar-uploader {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
 }

.avatar-uploader{
  border-color: var(--el-color-primary);
}

</style>